

#include <stdio.h>
#include <time.h> 


#include "stream_h264.h"

#ifdef ANDROID
#include <jni.h>
#include <android/log.h>
#define LOGE(format, ...)  __android_log_print(ANDROID_LOG_ERROR, "(>_<)", format, ##__VA_ARGS__)
#define LOGI(format, ...)  __android_log_print(ANDROID_LOG_INFO,  "(^_^)", format, ##__VA_ARGS__)
#else
#define LOGE(format, ...)  printf("(>_<) " format "\n", ##__VA_ARGS__)
#define LOGI(format, ...)  printf("(^_^) " format "\n", ##__VA_ARGS__)
#endif


//Output FFmpeg's av_log()
void custom_log(void *ptr, int level, const char* fmt, va_list vl){

	//To TXT file
	FILE *fp=fopen("/storage/emulated/0/av_log.txt","a+");
	if(fp){
		vfprintf(fp,fmt,vl);
		fflush(fp);
		fclose(fp);
	}

	//To Logcat
	//LOGE(fmt, vl);
}
//for test
//com.jemi.androidh264streamdemo//cn.five.stream


JNIEXPORT jint JNICALL Java_cn_five_stream_manager_NativeStream_stream
  (JNIEnv *env, jobject obj, jbyteArray input_jstr, jstring output_jstr, jint len, jint type)
{
//	char input_str[BUFFER_SIZE]={0};
	int nRet = 0;
	char output_str[500]={0};
	sprintf(output_str,"%s",(*env)->GetStringUTFChars(env, output_jstr, NULL));
	jbyte *m_temp = (*env)->GetByteArrayElements(env, input_jstr, 0);
    char *data=(char*)m_temp;
	m_nFileBufSize = len;
	m_pFileBuf = data;
	m_nCurPos = 0;
    signal(SIGPIPE, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
//init pushstream
//	if (!g_nInitFlag)
//	{
//		if (Net_Init(output_str) < 0)
//		{
//			LOGE("-----Net_Init--------\n");
//			return NETINIT_ERROR;
//		}
//		g_nInitFlag++;
//	}
	if (type == NET_INIT)  //0
	{
		if (Net_Init(output_str) < 0)
		{
			Close();
			return NETINIT_ERROR;
		}
	}
	if (type == SEND_VIDEIO_STREAM) //1
    {
		if ( (nRet = SendH264Stream(data)) <=0 )
		{
			if (!nRet)
			{
				return SEND_H264_ERROR;
			}
			return nRet;
		}
    }
	if (type == SEND_AUDIO_STREAM) //2
	{
		if ((nRet = SendAacStream(data, len)) <=0 )
		{
			if (!nRet)
			{
				return SEND_ACC_ERROR;
			}
			return nRet;
		}
	}
	if (type == CLOSE_STREAM) //3
	{
		Close();
	}

    return 0;
}
